#include "MainWindow.h"
#include "./ui_MainWindow.h"
#include <qDebug>
#include "DateTimeTask.h"
#include "ToolUtils.h"
#include "MotorController.h"
#include <QHostInfo>
#include <QTimer>

#define MAX_TIMER_TASK_NUM 100

static uint8_t setTimeFlag = 0;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    qRegisterMetaType<QHostAddress>("QHostAddress");
    ui->setupUi(this);
    initView();
    initTimeSetTimer();
    QTimer::singleShot(500, [this]() {
            QByteArray byteArray;
            byteArray.append(1, 4);
            byteArray.append(1, 4);
            byteArray.append(ToolUtils::CalculateCRC16(byteArray));
            QHostAddress address("192.168.1.255");
            udpThread->sendMessage(byteArray, address, 1025);

            QByteArray byteArray2;
            byteArray2.append(1, 5);
            byteArray2.append(1, 4);
            byteArray2.append(ToolUtils::CalculateCRC16(byteArray2));
            QHostAddress address2("192.168.1.255");
            udpThread->sendMessage(byteArray2, address2, 1025);
        // 这里可以执行更复杂的逻辑
        });
}

MainWindow::~MainWindow()
{
    m_timerThread->stop();
    m_timerThread->wait();
    delete m_timerThread;
    udpThread->requestInterruption();
    udpThread->wait();
    delete ui;
}

void MainWindow::initView()
{

    ui->tableWidget->setColumnCount(8);

    ui->tableWidget->setHorizontalHeaderLabels({ tr("year"), tr("month"), tr("date"), tr("hour"), tr("minute"), tr("period"), tr("speedA"), tr("speedB") }); //
    ui->tableWidget->setRowCount(MAX_TIMER_TASK_NUM);

    QDateTime d =  QDateTime::currentDateTime();

    for (int i = 0;i < MAX_TIMER_TASK_NUM;i++)
    {
        QTime da = d.time().addSecs(120*(i+1));
        ui->tableWidget->setItem(i, 0, new QTableWidgetItem(QString::number(d.date().year())));
        ui->tableWidget->setItem(i, 1, new QTableWidgetItem(QString::number(d.date().month())));
        ui->tableWidget->setItem(i, 2, new QTableWidgetItem(QString::number(d.date().day())));
        ui->tableWidget->setItem(i, 3, new QTableWidgetItem(QString::number(da.hour())));
        ui->tableWidget->setItem(i, 4, new QTableWidgetItem(QString::number(da.minute())));
        ui->tableWidget->setItem(i, 5, new QTableWidgetItem(QString::number(60)));
        ui->tableWidget->setItem(i, 6, new QTableWidgetItem(QString::number(60)));
        ui->tableWidget->setItem(i, 7, new QTableWidgetItem(QString::number(100)));
    }



    ui->tableWidget->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);


    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
    ui->dateTimeEdit->setDisplayFormat("yyyy-MM-dd HH:mm:ss");

    ui->dateTimeEdit->setDateTime(QDateTime::currentDateTime());

    ui->horizontalSlider->setMinimum(0);
    ui->horizontalSlider->setMaximum(100);

    ui->horizontalSlider_2->setMinimum(0);
    ui->horizontalSlider_2->setMaximum(100);

    udpThread = new UdpThread(this);
    connect(udpThread, &UdpThread::messageReceived, this, &MainWindow::onMessageReceived);
    udpThread->start();

}

void MainWindow::initTimeSetTimer()
{
    // ������ʱ�������߳�
    m_timerThread = new TimerControlThread(this);

    // �����źŲ�
    connect(m_timerThread, &TimerControlThread::timerTimeout, this, &MainWindow::onTimerTimeout);
    connect(m_timerThread, &TimerControlThread::timerStatusChanged, this, &MainWindow::onTimerStatusChanged);

    // �����߳�
    m_timerThread->start();

    // ������ʱ��
    m_timerThread->startTimer();
}

void MainWindow::onMessageReceived(const QByteArray& message, const QHostAddress& address, quint16 port)
{

    if (isLocalIp(address.toString()))
    {
        return;
    }
    qDebug() << "IP Address2:" << address.toString();
    qDebug() << "recevice:" << message.toHex();


    if (message.toHex().mid(0,2).toInt() == 0x04)
    {
        if (message.toHex().mid(2, 2).toInt() == 0)
        {
            ui->label_7->setText(tr("停止"));
        }
        else
        {
            ui->label_7->setText(tr("启动"));
        }

        if (message.toHex().mid(8, 2).toInt() == 0)
        {
            ui->label_10->setText(tr("停止"));
        }
        else
        {
            ui->label_10->setText(tr("启动"));
        }

        if (message.toHex().mid(14, 2).toInt() == 0)
        {
            ui->label_13->setText(tr("停止"));
        }
        else
        {
            ui->label_13->setText(tr("启动"));
        }

        if (message.toHex().mid(6, 2).toInt() == 0)
        {
            ui->label_8->setText(tr("正向"));
        }
        else
        {
            ui->label_8->setText(tr("反向"));
        }

        if (message.toHex().mid(12, 2).toInt() == 0)
        {
            ui->label_11->setText(tr("正向"));
        }
        else
        {
            ui->label_11->setText(tr("反向"));
        }

        if (message.toHex().mid(18, 2).toInt() == 0)
        {
            ui->label_14->setText(tr("正向"));
        }
        else
        {
            ui->label_14->setText(tr("反向"));
        }


        ui->label_5->setText(tr("电机1速度控制") + ":" + QString::number(100 -  message.toHex().mid(4, 2) .toInt(nullptr,16)) + "%");
        ui->label_6->setText(tr("电机2速度控制") + ":" + QString::number(100 - message.toHex().mid(10, 2).toInt(nullptr, 16)) + "%");
        ui->label_16->setText(tr("电机3速度控制") + ":" + QString::number(100 - message.toHex().mid(16, 2).toInt(nullptr, 16)) + "%");
    }
    else if (message.toHex().mid(0, 2).toInt(nullptr, 16) == 0x05)
    {
        timearray.clear();
        timearray.append(message.mid(1,7));
        setTimeFlag = 1;
    }


}
void MainWindow::on_pushButton_10_clicked()
{
    quint8 count = 0;
    QByteArray total;
    total.clear();
    for (int row = 0; row < ui->tableWidget->rowCount(); ++row) {
        bool flag = false;
        DateTimeTask* de = new DateTimeTask(this);
        for (int col = 0; col < ui->tableWidget->columnCount(); ++col) {
            QTableWidgetItem* item = ui->tableWidget->item(row, col);
            if (item) {
               // qDebug() << "Item at (" << row << "," << col << "):" << item->text();
                if (!ToolUtils::isPureInteger(item->text()))
                {
                    flag = true;
                }
            }
            else
            {
                flag = true;
            }
        }
        if (!flag)
        {
            de->setYear(ui->tableWidget->item(row, 0)->text().toInt() - 2000);
            de->setMonth(ui->tableWidget->item(row, 1)->text().toInt());
            de->setDate(ui->tableWidget->item(row, 2)->text().toInt());
            de->setHour(ui->tableWidget->item(row, 3)->text().toInt());
            de->setMinute(ui->tableWidget->item(row, 4)->text().toInt());
            de->setPeriod(ui->tableWidget->item(row, 5)->text().toInt());
            de->setSpeedA(100 - ui->tableWidget->item(row, 6)->text().toInt());
            de->setSpeedB(100 - ui->tableWidget->item(row, 7)->text().toInt());
            total.append(de->getByteArray());
            count++;
        }

        delete de;
    }

    qDebug() << "count: " << count;
    if (total.isEmpty())
    {
        qDebug() << "total.isEmpty()";
    }
    else
    {
        QByteArray byteArray;
        byteArray.append(1, 3);
        byteArray.append(1, count);
        byteArray.append(total);
        byteArray.append(ToolUtils::CalculateCRC16(byteArray));
        QHostAddress address("192.168.1.255");

        udpThread->sendMessage(byteArray, address, 1025);
        qDebug() << "Hexadecimal representation:" << byteArray.toHex();
    }
}


void MainWindow::on_pushButton_clicked()
{
    QByteArray byteArray;
    byteArray.append(1, 1);
    byteArray.append(1, 1);
    byteArray.append(1, 1);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);

}


void MainWindow::on_pushButton_2_clicked()
{
    QByteArray byteArray;
    byteArray.append(1, 1);
    byteArray.append(1, 1);
    byteArray.append(1, 0);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));
    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}


void MainWindow::on_pushButton_7_clicked()
{
    int year = ui->dateTimeEdit->date().year();
    int month = ui->dateTimeEdit->date().month();
    int date = ui->dateTimeEdit->date().day();
    int hour = ui->dateTimeEdit->time().hour();
    int minute = ui->dateTimeEdit->time().minute();
    int second = ui->dateTimeEdit->time().second();
    int day = ui->dateTimeEdit->date().dayOfWeek();

    QByteArray byteArray;
    byteArray.append(1, 2);
    byteArray.append(1, year - 2000);
    byteArray.append(1, month);
    byteArray.append(1, date);
    byteArray.append(1, hour);
    byteArray.append(1, minute);
    byteArray.append(1, second);
    byteArray.append(1, day);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));
    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}


void MainWindow::on_pushButton_3_clicked()
{
    QByteArray byteArray;
    byteArray.append(1, 1);
    byteArray.append(1, 2);
    byteArray.append(1, 1);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}


void MainWindow::on_pushButton_4_clicked()
{
    QByteArray byteArray;
    byteArray.append(1, 1);
    byteArray.append(1, 2);
    byteArray.append(1, 0);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}


void MainWindow::on_pushButton_5_clicked()
{
    QByteArray byteArray;
    byteArray.append(1, 1);
    byteArray.append(1, 3);
    byteArray.append(1, 1);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}


void MainWindow::on_pushButton_6_clicked()
{
    QByteArray byteArray;
    byteArray.append(1, 1);
    byteArray.append(1, 3);
    byteArray.append(1, 0);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}

void MainWindow::onTimerTimeout()
{
    ui->dateTimeEdit->setDateTime(QDateTime::currentDateTime());
    int day = MotorController::getInstance()->day();
    int month = MotorController::getInstance()->month();
    int year = MotorController::getInstance()->year();
    int de = timearray.size();

    if (setTimeFlag == 1)
    {
        setTimeFlag = 0;
        uint8_t year = timearray.toHex().mid(0,2).toInt(nullptr, 16);
        uint8_t month = timearray.toHex().mid(2, 2).toInt(nullptr, 16);
        uint8_t date = timearray.toHex().mid(4, 2).toInt(nullptr, 16);
        uint8_t hour = timearray.toHex().mid(6, 2).toInt(nullptr, 16);
        uint8_t minute = timearray.toHex().mid(8, 2).toInt(nullptr, 16);
        uint8_t second = timearray.toHex().mid(10, 2).toInt(nullptr, 16);

        qDebug() << year;

        QDate date2(year+2000, month, date);

        // 创建 QTime 对象
        QTime time(hour, minute, second);

        // 使用 QDate 和 QTime 创建 QDateTime
        QDateTime myDateTime2(date2, time);

        myDateTime = myDateTime2;

        ui->label_4->setText(tr("设备当前时间:") + myDateTime.toString("yyyy-MM-dd HH:mm:ss"));
    }
    else
    {
        myDateTime = myDateTime.addSecs(1);
        ui->label_4->setText(tr("设备当前时间:") + myDateTime.toString("yyyy-MM-dd HH:mm:ss"));
    }
} 

void MainWindow::onTimerStatusChanged(bool isRunning)
{

    qDebug() << "Timer status changed:" << (isRunning ? "Running" : "Stopped");

}


void MainWindow::on_horizontalSlider_sliderReleased()
{
    int value = ui->horizontalSlider->value();
    qDebug() << "value:" << value;

    ui->label_5->setText(tr("电机1速度控制")+ ":" + QString::number(value) + "%");

    QByteArray byteArray;
    byteArray.append(1, 7);
    byteArray.append(1, 1);
    byteArray.append(1, 100 - value);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}



void MainWindow::on_horizontalSlider_2_sliderReleased()
{
   int value = ui->horizontalSlider_2->value();
   qDebug() << "value_2:" << value;

   ui->label_6->setText(tr("电机2速度控制") + ":" + QString::number(value) + "%");

   QByteArray byteArray;
   byteArray.append(1, 7);
   byteArray.append(1, 2);
   byteArray.append(1, 100 - value);
   byteArray.append(ToolUtils::CalculateCRC16(byteArray));

   QHostAddress address("192.168.1.255");
   udpThread->sendMessage(byteArray, address, 1025);
}

void MainWindow::on_horizontalSlider_3_sliderReleased()
{
    int value = ui->horizontalSlider_3->value();
    qDebug() << "value_3:" << value;

    ui->label_16->setText(tr("电机3速度控制") + ":" + QString::number(value) + "%");

    QByteArray byteArray;
    byteArray.append(1, 7);
    byteArray.append(1, 3);
    byteArray.append(1, 100 - value);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}


void MainWindow::on_pushButton_9_clicked()
{
    QByteArray byteArray;
    byteArray.append(1, 5);
    byteArray.append(1, 4);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));
    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}


void MainWindow::on_pushButton_12_clicked()
{
    QByteArray byteArray;
    byteArray.append(1, 8);
    byteArray.append(1, 1);
    byteArray.append(1, 1);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}


void MainWindow::on_pushButton_11_clicked()
{
    QByteArray byteArray;
    byteArray.append(1, 8);
    byteArray.append(1, 1);
    byteArray.append(1, 0);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}


void MainWindow::on_pushButton_13_clicked()
{
    QByteArray byteArray;
    byteArray.append(1, 8);
    byteArray.append(1, 2);
    byteArray.append(1, 1);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}


void MainWindow::on_pushButton_14_clicked()
{
    QByteArray byteArray;
    byteArray.append(1, 8);
    byteArray.append(1, 2);
    byteArray.append(1, 0);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}


void MainWindow::on_pushButton_15_clicked()
{
    QByteArray byteArray;
    byteArray.append(1, 8);
    byteArray.append(1, 3);
    byteArray.append(1, 1);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}


void MainWindow::on_pushButton_16_clicked()
{
    QByteArray byteArray;
    byteArray.append(1, 8);
    byteArray.append(1, 3);
    byteArray.append(1, 0);
    byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    QHostAddress address("192.168.1.255");
    udpThread->sendMessage(byteArray, address, 1025);
}


void MainWindow::on_pushButton_8_clicked()
{
    //QByteArray byteArray;
    //byteArray.append(1, 6);
    //byteArray.append(1, 4);
    //byteArray.append(ToolUtils::CalculateCRC16(byteArray));

    //QHostAddress address("192.168.1.255");
    //udpThread->sendMessage(byteArray, address, 1025);
}

bool MainWindow::isLocalIp(const QString &myIp) {
    QHostInfo info = QHostInfo::fromName(QHostInfo::localHostName());
    if (info.error() != QHostInfo::NoError) {
        qDebug() << "Error:" << info.errorString();
        return true;
    }
    const auto addresses = info.addresses();
    for (const QHostAddress& address : addresses) {
        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            //qDebug() << "IP Address:" << address.toString();
            if (myIp.contains(address.toString()))
            {
                return true;
            }
        }
    }
    return false;
}

